package com.lagou.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

     String requestMsg;

     String responseMsg;

     ChannelHandlerContext channelHandlerContext;

    /**
     * 设置发送消息
     */
    public void requestMsg(String msg){
        this.requestMsg = msg;
    }


    /**
     * 通道连接事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelHandlerContext =ctx;
    }

    /**
     * 通道读取就绪事件
     * @param channelHandler
     * @param s
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandler, String s) throws Exception {
        responseMsg=s;
        notify();
    }


    @Override
    public synchronized Object call() throws Exception {
        channelHandlerContext.writeAndFlush(requestMsg);
        wait();
        return responseMsg ;
    }
}
